/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LXW
 * Date: 2022-04-04
 * Time: 20:30
 */
public class MyHashBuck {
    class Node {
        public int key;
        public int val;
        public Node next;
        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }
    private static final double DEFAULT_FACTORY = 0.75;
    private Node[] array;
    private int size;
    public MyHashBuck() {
        this.array = new Node[8];
        this.size = 0;
    }
    public void put(int key, int val) {
        int index = key % array.length;
        Node node = new Node(key,val);
        Node cur = array[index];
        while(cur != null) {
            if(cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //使用头插
        node.next = array[index];
        array[index] = node;
        size++;
        if(factory(array,size) >= DEFAULT_FACTORY) {
            resize();
        }
    }
    public double factory(Node[] array,int size) {
        int len = array.length;
        return 1.0*len / size;
    }
    public void resize() {
        Node[] newArray = new Node[array.length];
        for(int i = 0 ; i < array.length; i++) {
            if(array[i] != null) {
                Node cur = array[i];
                while (cur != null) {
                    Node curNext = cur.next;
                    int index = cur.key % newArray.length;
                    cur.next = newArray[index];
                    newArray[index] = cur;
                    cur = curNext;
                }

            }

        }
        array = newArray;
    }
    public int get(int key) {
        int index = size % array.length;
        Node cur = array[index];
        while(cur != null) {
            if(cur.key == key) {
                return cur.val;
            }
        }
        return -1;
    }
}
